import Nifi from "../../nifi";
import {h} from "vue"
import { ElMessage } from "element-plus"
import ListEl from "./list.vue";
import DetailEl from "./detail.vue"
import {ts} from "../../i18n"


const t = ts('quene.index')

export default (nifi: Nifi) => {


    const getList = async (id: string) => {
        let uri = `/nifi-api/flowfile-queues/${id}/listing-requests`
        let res: any
        try {
            res = await nifi.api.post(uri,{})
            //
            uri += '/' + res.listingRequest.id;
            res = await nifi.api.get(uri);
            await nifi.api.delete(uri)
        } catch (error) {
            console.error(error)
            ElMessage.error('获取列表数据失败 :: ' + error)
        }
        if (res.listingRequest) {
            return res.listingRequest;
        }
        return undefined;
    }

    const getFlowfiles = async (id: string, uid: string) => {
        const uri = `/nifi-api/flowfile-queues/${id}/flowfiles/${uid}`
        try {
            const res = await nifi.api.get(uri);
            return res.flowFile;
        } catch (error) {
            console.error(error)
            ElMessage.error('获取 flowfiles 数据失败 :: ' + error)
        }
        return undefined;
    }

    const getContent = async (id: string, uid: string) => {
        const uri = `/nifi-api/flowfile-queues/${id}/flowfiles/${uid}/content?clientId=${nifi.flow.clientId}'`
        const res = await nifi.api.get(uri,{type:'arrayBuffer'})
        return res;
    }

    const downContent = (id: string, uid: string, name?: string) => {
        const url = `/nifi-api/flowfile-queues/${id}/flowfiles/${uid}/content?clientId=${nifi.flow.clientId}'`
        const n = name || `content.${new Date().getTime()}.txt`
        nifi.api.download(url, n)
    }


    const open = (id:string) => {
        return nifi.box.dialog((box) => h(ListEl, { nifi, id, onClose: () => box.close() }), { title: t('title.quene list'), showFooter: false })
    }

    const openDetail = (id:string,uuid:string) => {
        return nifi.box.dialog((box) => h(DetailEl, { nifi, id,uuid, onClose: () => box.close() }), { title: t('title.flow file'), showFooter: false })

    }

    const openContent = () => {

    }



    return {
        getList,
        getFlowfiles,
        getContent,
        downContent,
        open,
        openDetail,
        ListEl
    }

}